#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/4/15 15:40
# @Author  : Chenmm
# @File    : SysMenu.py
# @Software: PyCharm

from app import db
from datetime import datetime


class SysMenu(db.Model):
    __tablename__ = 'sys_menu'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='ID')
    parent_id = db.Column(db.BigInteger, nullable=False, comment='父菜单ID')
    tree_path = db.Column(db.String(255), comment='父节点ID路径')
    name = db.Column(db.String(64), nullable=False, comment='菜单名称')
    type = db.Column(db.SmallInteger, nullable=False, comment='菜单类型')
    route_name = db.Column(db.String(255), comment='路由名称')
    route_path = db.Column(db.String(128), comment='路由路径')
    component = db.Column(db.String(128), comment='组件路径')
    perm = db.Column(db.String(128), comment='权限标识')
    always_show = db.Column(db.SmallInteger, default=0, comment='是否始终显示')
    keep_alive = db.Column(db.SmallInteger, default=0, comment='是否开启缓存')
    visible = db.Column(db.SmallInteger, default=1, comment='显示状态')
    sort = db.Column(db.Integer, default=0, comment='排序')
    icon = db.Column(db.String(64), comment='菜单图标')
    redirect = db.Column(db.String(128), comment='跳转路径')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, onupdate=datetime.now, comment='更新时间')
    params = db.Column(db.String(255), comment='路由参数')

    __table_args__ = {'comment': '菜单管理'}

    def to_router_json(self):
        router = {
            'name': self.route_path.capitalize() if self.route_path else '',
            'path': self.route_path,
            'redirect': self.redirect,
            'component': self.component,
            'meta': {
                'alwaysShow': True if self.always_show == 1 else False,
                'hidden': False if self.visible == 1 else True,
                'title': self.name,
                'icon': self.icon,
                'params': self.params,
                'keepAlive': True if self.keep_alive == 1 else False

            },
            'children': [menu.to_router_json() for menu in SysMenu.query.filter_by(parent_id=self.id).all() if menu.type == 1 or menu.type == 2]
        }

        if not router['children']:
            del router['children']
            del router['redirect']

        return router
